package bsf.baseservice.businessmq.redis.messagelock;

import bsf.base.BsfException;
import bsf.base.CallBack;
import bsf.base.TimeSpan;

/**
 消息合并，消息锁定
 主要为是了减少redis的消息通信和消息处理.(目前机制尚不能完全解决和消息合并，但是可以达到较好效果)
 
*/
public class BaseMessageLock
{
	protected Object lock = new Object(); //对象锁
	protected boolean isLock = false; //是否锁定对象
	protected boolean isHaveNewMessage = false; //是否有新消息
	protected TimeSpan mergeTime; //合并多少时间内消息

	public BaseMessageLock(TimeSpan mergetime)
	{
		mergeTime = mergetime;
	}

	public void lock(CallBack.Func0 action)
	{
	}

	protected  void lockRun(CallBack.Func0 action)
	{
		synchronized (lock) //并发锁,进行并发合并
		{
			try
			{
				isLock = true;
				while (isHaveNewMessage == true) //500ms内的请求合并
				{
					isHaveNewMessage = false;
					try
					{
						action.invoke();
					}
					catch (Exception exp)
					{
						throw exp;
					}
					finally
					{
						try{Thread.sleep((int)mergeTime.getMilliSeconds());}catch(Exception e) {}
					}
				}
			}
			catch (Exception exp)
			{
				throw new BsfException("LockRun出错", exp,this.getClass());
			}
			finally
			{
				isLock = false;
			}
		}

	}

}